#pragma 

#include <iostream>
#include <string>
#include <sys/epoll.h>
#include "Log.hpp"
#include "Err.hpp"

static const int defaultepfd = -1;
static const int gsize = 1024;

class Epoller {
public:
    Epoller() : epfd_(defaultepfd)
    {}

    void Create(int size = gsize) {
        epfd_ = epoll_create(size);
        if (epfd_ < 0)
        {
            logMessage(FATAL, "epoll create error, code: %d, errstring: %s", errno, strerror(errno));
            exit(EPOLL_CREATE_ERROR);
        }
    } 

    // 用户->内核 关心sock上的event事件
    bool AddEvent(int fd, uint32_t events) {
        struct epoll_event ev;
        ev.events = events;
        ev.data.fd = fd;           // 用户数据
        int n = epoll_ctl(epfd_, EPOLL_CTL_ADD, fd, &ev);

        if (n < 0) {
            logMessage(ERROR, "epoll control error, code: %d, errstring: %s", errno, strerror(errno));
            return false;
        }
        return true;
    }

    bool DelEvent(int fd) {
        return epoll_ctl(epfd_, EPOLL_CTL_DEL, fd, nullptr) == 0;
    }

    int Wait(struct epoll_event *revs, int num, int timeout) {
        return epoll_wait(epfd_, revs, num, timeout);
    }


    

    int Fd() {
        return epfd_;
    }

    void Close() {
        if (epfd_ != defaultepfd) close(epfd_);
    }

    ~Epoller() {

    }

private:
    int epfd_;
};